package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ProductApiService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sunjipu
 * @create 2020-04-07 15:33
 */
@Service
public class ProductApiServiceImpl implements ProductApiService {

    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        try {
            String key = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(key);

            //判断缓存是否存在
            if (null == skuInfo) {
                //不存在 ：上锁
                //使用Redis  Redisson   缓存三大问题 ： 穿透 雪崩 击穿
                RLock lock = redissonClient.getLock(key + ":lock");
                boolean res = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (res) {
                    //获取到了锁
                    try {
                        //查询数据库
                        skuInfo = getSkuInfoDB(skuId);
                        if (null == skuInfo) {
                            //此时就是穿透
                            SkuInfo skuInfo1 = new SkuInfo();
                            redisTemplate.opsForValue().set(skuId, skuInfo1, RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo1;
                        } else {
                            redisTemplate.opsForValue().set(skuId, skuInfo, RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo;
                        }
                    } catch (Exception e) {
                        e.getStackTrace();
                    } finally {
                        //解锁
                        if(lock.isLocked()){
                            lock.unlock();
                        }

                    }
                } else {
                    //直接查询缓存
                    return (SkuInfo) redisTemplate.opsForValue().get(key);
                }

            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return getSkuInfoDB(skuId);
    }
//    @Override
//    public SkuInfo getSkuInfo(Long skuId) {
//        String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
//
//        //  分布式锁
//        SkuInfo skuInfo = (SkuInfo)redisTemplate.opsForValue().get(skuKey);
//        if (null == skuInfo){
//            skuInfo =  getSkuInfoDB(skuId);
//            this.redisTemplate.opsForValue().set(skuKey, skuInfo);
//
//        }
//
////        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
////        // 根据skuId 查询图片列表集合
////        QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
////        queryWrapper.eq("sku_id", skuId);
////        List<SkuImage> skuImageList = skuImageMapper.selectList(queryWrapper);
////
////        skuInfo.setSkuImageList(skuImageList);
//        return skuInfo;
//    }
//
    public SkuInfo getSkuInfoDB(Long skuId){
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        // 根据skuId 查询图片列表集合
        QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id", skuId);
        List<SkuImage> skuImageList = skuImageMapper.selectList(queryWrapper);

        skuInfo.setSkuImageList(skuImageList);
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null != skuInfo) {
            return skuInfo.getPrice();
        }
        return new BigDecimal("0");
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);
    }
    @Override
    public Map getSkuValueIdsMap(Long spuId) {
        Map<Object, Object> map = new HashMap<>();
        // key = 125|123 ,value = 37
        List<Map> mapList = skuSaleAttrValueMapper.getSaleAttrValuesBySpu(spuId);
        if (mapList != null && mapList.size() > 0) {
            // 循环遍历
            for (Map skuMap : mapList) {
                // key = 125|123 ,value = 37
                map.put(skuMap.get("value_ids"), skuMap.get("sku_id"));
            }
        }
        return map;
    }

    @Override
    @GmallCache(prefix = "category")
    public List<JSONObject> getBaseCategoryList() {
        List<JSONObject> list = new ArrayList<>();
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        int index = 1;
        for(Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()){
            Long category1Id = entry1.getKey();
            List<BaseCategoryView> category2List1 = entry1.getValue();

            JSONObject category1 = new JSONObject();
            //添加角标
            category1.put("index", index);
            //一级分类ID
            category1.put("categoryId", category1Id);
            //一级分类名字
            category1.put("categoryName", category2List1.get(0).getCategory1Name());
            index++;
            //二级分类子节点
            //查询二级分类集合
            Map<Long, List<BaseCategoryView>> category2Map = category2List1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //List<BaseCategoryView> category2List = category2Map.get(mapKey);
            List<JSONObject> category2Child = new ArrayList<>();
            for(Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
                Long category2Id = entry2.getKey();
                List<BaseCategoryView> category3List = entry2.getValue();

                JSONObject category2 = new JSONObject();
                //二级分类ID
                category2.put("categoryId", category2Id);
                //二级分类名字
                category2.put("categoryName", category3List.get(0).getCategory2Name());
                //三级级分类子节点
                //查询三级级分类集合
                List<JSONObject> category3Child = new ArrayList<>();
                category3List.stream().forEach(category3View -> {
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", category3View.getCategory3Id());
                    category3.put("categoryName", category3View.getCategory3Name());
                    category3Child.add(category3);
                });
                category2Child.add(category2);
                category2.put("categoryChild", category3Child);
            }
            category1.put("categoryChild", category2Child);
            list.add(category1);
        }
        return list;
    }

    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    @Override
    public List<SkuAttrValue> getAttrList(Long skuId) {

        return skuAttrValueMapper.selectSkuAttrValueListBySkuId(skuId);
    }


}
